package com.wash.shoes.controller.dy;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.domain.R;
import com.wash.shoes.domain.dto.BuyGoodsDto;
import com.wash.shoes.domain.dto.MobileOrderDto;
import com.wash.shoes.domain.jd.JdOrderService;
import com.wash.shoes.domain.order.SaveOrderComponent;
import com.wash.shoes.entity.ShopGoodsPo;
import com.wash.shoes.exception.WashException;
import com.wash.shoes.resp.ShopAndFactoryPair;
import com.wash.shoes.service.ShopGoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author ljg
 * @since 2024-08-29
 */
@Log4j2
@Api(tags = {"抖音-洗护订单"})
@RestController
@RequestMapping("/mobile-api/order")
public class OrderDController {

    @Resource
    JdOrderService jdOrderService;

    @Resource
    ShopGoodsService shopGoodsService;

    @Resource
    SaveOrderComponent saveOrderComponent;

    @ApiOperation("检查用户的地址")
    @PostMapping("/checkUserAddress")
    @Transactional
    public R<String> checkUserAddress(@RequestBody MobileOrderDto mobileOrder) {

        // ShopPo shopPo = saveOrderComponent.getShopPo(mobileOrder);
        log.info("开始检查用户地址:{}", mobileOrder);
        String goodId = null;
        if (CollectionUtil.isNotEmpty(mobileOrder.getShopGoodsInfo())) {
            goodId = mobileOrder.getShopGoodsInfo().get(0).getShopGoodsId();
        }
        /*FactoryPo shopPo*/
        ShopAndFactoryPair shopAndFactoryPair = saveOrderComponent.getShopPo(mobileOrder, null, goodId);
        // 检查物流地址检查
        String result = jdOrderService.preCheckAddress(mobileOrder.getReceiveUserAddress().getReceiverAddress(),
                shopAndFactoryPair.getFactoryPo().getFactoryAddress());
        log.info("地址检查的结果为: [{}]", result);
        if (!"success".equals(result)) {
            throw new WashException(
                    result + "[" + mobileOrder.getReceiveUserAddress().getReceiverAddress() + "],请输入详细地址");
        }
        // 检查是否可以下单
        // saveOrderComponent.verifyGetShop(mobileOrder); TODO 上面已经验证,这里就不需要了
        // 检查商品是否下架
        for (BuyGoodsDto buyGoodsDto : mobileOrder.getShopGoodsInfo()) {
            ShopGoodsPo shopGoodsPo = shopGoodsService.getById(buyGoodsDto.getShopGoodsId());
            if (shopGoodsPo.getStatus() != 1) {
                throw new WashException("商品已经下架请联系管理员");
            }
        }
        return R.ok();
    }

}
